/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.me.nicefotoappcamp;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.widget.RemoteViews;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.me.nicefotoappcamp.MainActivity;
import org.me.nicefotoappcamp.R;
import org.me.nicefotoappcamp.core.Picture;
import org.me.nicefotoappcamp.provider.Provider;
import org.me.nicefotoappcamp.provider.fotokudra.FotoKudraProvider;

/**
 *
 * @author Tautvydas
 */
public class NiceFotoAppWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];

            Intent intent = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            Provider kudra = new FotoKudraProvider();
            ArrayList<Picture> pictures = kudra.getPictures();
            int num = (int)Math.random()*(pictures.size()-1);
            Picture pic = pictures.get(i);


            //ImageView g = (ImageView) findViewById(R.id.frame);
            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.nicefoto_appwidget);
            System.out.println("labas");
            views.setOnClickPendingIntent(R.id.frame, createOnClickIntent(context, appWidgetId));            //views.setImageViewBitmap(R.id.frame, pic.getBitmap());
            System.out.println("gogo");
            try {
                //views.setImageViewBitmap(R.id.frame, frameBitmap(context, "geras", pic.getBitmap(), "vel", "data"));
                views.setImageViewBitmap(R.id.frame, pic.getBitmap());
                //views.set
            } catch (Exception ex) {
                Logger.getLogger(NiceFotoAppWidgetProvider.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Tell the AppWidgetManager to perform an update on the current App Widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    private PendingIntent createOnClickIntent(Context context, int appWidgetId) {
    	Intent intent = new Intent(context, MainActivity.class);
    	intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private Bitmap frameBitmap(Context context, String frame, Bitmap bitmap, String summaryOrTitle, String published) throws Exception {
    	final int SPACE = 5;
    	final int TEXT_SIZE_SUMMARY_OR_TITLE = 18;
    	final int TEXT_SIZE_PUBLISHED = 15;
    	final float FRAME_WIDTH = 294;
    	final float FRAME_HEIGHT = 220;
		Bitmap leftAbove = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_left_above", frame)).getInt(null));
		Bitmap rightAbove = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_right_above", frame)).getInt(null));
		Bitmap leftBottom = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_left_bottom", frame)).getInt(null));
		Bitmap rightBottom = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_right_bottom", frame)).getInt(null));
		Bitmap above = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_above", frame)).getInt(null));
		Bitmap bottom = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_bottom", frame)).getInt(null));
		Bitmap left = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_left", frame)).getInt(null));
		Bitmap right = BitmapFactory.decodeResource(context.getResources(), R.drawable.class.getField(String.format("frame_%s_right", frame)).getInt(null));
    	Bitmap ixonosLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_image);
    	Bitmap output = Bitmap.createBitmap(bitmap.getWidth() + leftAbove.getWidth() + rightAbove.getWidth(),
    										bitmap.getHeight() + leftAbove.getHeight() + leftBottom.getHeight(),
    										Config.ARGB_8888);
    	// draw photo frame
    	Canvas canvas = new Canvas(output);
    	canvas.drawBitmap(bitmap, leftAbove.getWidth(), leftAbove.getHeight(), null);
    	canvas.drawBitmap(leftAbove, 0, 0, null);
    	canvas.drawBitmap(rightAbove, left.getWidth() + bitmap.getWidth(), 0, null);
    	canvas.drawBitmap(leftBottom, 0, above.getHeight() + bitmap.getHeight(), null);
    	canvas.drawBitmap(rightBottom, left.getWidth() + bitmap.getWidth(), above.getHeight() + bitmap.getHeight(), null);
    	canvas.drawBitmap(above, new Rect(0, 0, bitmap.getWidth(), above.getHeight()),
    						new Rect(left.getWidth(), 0, bitmap.getWidth() + left.getWidth(), above.getHeight()), null);
    	canvas.drawBitmap(bottom, new Rect(0, 0, bitmap.getWidth(), bottom.getHeight()),
							new Rect(left.getWidth(), above.getHeight() + bitmap.getHeight(),
									 	left.getWidth() + bitmap.getWidth(), output.getHeight()), null);
    	canvas.drawBitmap(left, new Rect(0, 0, left.getWidth(), bitmap.getHeight()),
    						new Rect(0, above.getHeight(), left.getWidth(), above.getHeight() + bitmap.getHeight()), null);
    	canvas.drawBitmap(right, new Rect(0, 0, right.getWidth(), bitmap.getHeight()),
    						new Rect(left.getWidth() + bitmap.getWidth(), above.getHeight(), output.getWidth(),
    								above.getHeight() + bitmap.getHeight()), null);
    	// draw summary or title
    	Paint paintSummaryOrTitle = new Paint();
    	paintSummaryOrTitle.setColor(context.getResources().getColor(R.color.ixonos_color));
    	paintSummaryOrTitle.setTypeface(Typeface.DEFAULT_BOLD);
    	paintSummaryOrTitle.setTextSize(TEXT_SIZE_SUMMARY_OR_TITLE);
    	canvas.drawText(summaryOrTitle, left.getWidth() + SPACE, above.getHeight() + TEXT_SIZE_SUMMARY_OR_TITLE, paintSummaryOrTitle);
    	// draw published
    	Paint paintPublished = new Paint();
    	paintPublished.setColor(context.getResources().getColor(R.color.ixonos_color));
    	paintPublished.setTypeface(Typeface.DEFAULT_BOLD);
    	paintPublished.setTextSize(TEXT_SIZE_PUBLISHED);
    	canvas.drawText(published, left.getWidth() + SPACE, above.getHeight() + TEXT_SIZE_SUMMARY_OR_TITLE + TEXT_SIZE_PUBLISHED, paintPublished);
    	// draw Ixonos logo
    	canvas.drawBitmap(ixonosLogo, left.getWidth() + SPACE, above.getHeight() + bitmap.getHeight() - ixonosLogo.getHeight() - SPACE, null);
    	// scale image
    	if (output.getWidth() > FRAME_WIDTH && output.getHeight() > FRAME_HEIGHT) {
	    	if (output.getWidth() >= output.getHeight()) {
	    		float ratio = (float)output.getWidth() / FRAME_WIDTH;
	    		output = Bitmap.createScaledBitmap(output, (int)FRAME_WIDTH, (int)((float)output.getHeight() / ratio), true);
	    	} else {
	    		float ratio = (float)output.getHeight() / FRAME_HEIGHT;
	    		output = Bitmap.createScaledBitmap(output, (int)((float)output.getWidth() / ratio), (int)FRAME_HEIGHT, true);
	    	}
    	}
    	return output;
    }
}
